
import re
import sys


def replace_keywords_in_file(file_path, old_keyword, new_keyword):
    try:
        # 打开文件并读取内容
        with open(file_path, 'r', encoding='ISO-8859-1') as file:
            content = file.read()
            byte_data = content.encode('ISO-8859-1')
            correct_text = byte_data.decode('GBK')

        # print(correct_text)
        # 替换关键字
        new_text = re.sub(old_keyword,new_keyword, correct_text)
        byte_data_new = new_text.encode("GBK")
        new_text_c = byte_data_new.decode("ISO-8859-1")


        # 将替换后的内容写回到文件中
        with open(file_path, 'w', encoding='ISO-8859-1') as file:
            
            file.write(new_text_c)

        print(f"成功将文件 {file_path} 中的 '{old_keyword}' 替换为 '{new_keyword}'")
    except FileNotFoundError:
        print(f"错误：文件 {file_path} 未找到。")
    except Exception as e:
        print(f"发生未知错误：{e}")


# 示例使用
if __name__ == "__main__":
    file_path = sys.argv[1]
    old_keyword = sys.argv[2]
    new_keyword = sys.argv[3]
    replace_keywords_in_file(file_path, old_keyword, new_keyword)
    